#include <go32.h>
#include <sys/farptr.h>
#include <string.h>
#include <stdio.h>
#include "video-text.h"

#define canto_sup_esq 0xc9
#define canto_sup_dir 0xbb
#define canto_inf_esq 0xc8
#define canto_inf_dir 0xbc
#define traco_hor 0xcd
#define traco_ver 0xba

/** Print character ch at position x,y with attributes
* return true if sucessfull
*/
Bool printCharAt(char ch, int x, int y, char attributes)
{
	// Verifica se a posi,cao onde se pretende escrever  pode ser acedida
	if(x > 24 || x < 0 || y < 0 || y > 79)
		return false;

	unsigned long offset = x*(80*2) + y*2;
	
	_farpokeb(_dos_ds, VIDEO_TEXT + offset , ch );
	_farpokeb(_dos_ds, VIDEO_TEXT + offset +1, attributes);
	
	return true;
}

/** Print character array str at position x,y with attributes
* return true if sucessfull
*/
Bool printStringAt(char *str, int x, int y, char attributes)
{
	unsigned int i;
	Bool erro = false;
	
	for(i = 0; i < strlen(str); i++)
	{
		erro = printCharAt(str[i],x,y++,attributes);
	
		// Se a posi,cao pretendida para o caracter ultrapassar o limite da janela, entao retorna false
		if(!erro)
			return false;
		
	}
	
	return true;
}

/** Print integer num at position x,y with attributes.
* No C library function is used.
* return true if sucessfull
*/
Bool printIntAt(int num, int x, int y, char attributes)
{

	char caracter;
	
	int temp = num;
	int num_len = 0;
	int i;
	
	// Conta o numero de algarismos
	while(temp != 0)
	{
		temp /= 10;
		num_len++;
	}
	
	Bool erro = false;
	
	// Escreve  o numero caracter a caracter
	for(i=num_len; i > 0; i--)
	{
		caracter = num%10;
		num /= 10;
	
		erro = printCharAt(caracter+'0', x, y+i, attributes);	

			if(!erro)
				return false;
	}

	return true;
}

/** Draw rectangular frame with left upper corner at position x,y
* with width and height dimensions, decorated with title attributes.
* return true if sucessfull
*/

Bool drawFrame(char *title, char attributes,int x, int y, int width, int height)
{

	int i = 1;
	int j = 1;
	
	printCharAt(canto_sup_esq, 0+x, 0+y, attributes);
	printCharAt(canto_sup_dir, 0+x, height - 1+y, attributes);
	printCharAt(canto_inf_esq, width - 1+x, 0+y, attributes);
	printCharAt(canto_inf_dir, width - 1+x, height - 1+y, attributes);
	
	while ( j != height - 1)
	{
		printCharAt(traco_hor, x, j+y, attributes);
		printCharAt(traco_hor, width-1+x, j+y, attributes);
	
		j++;
	}

	while( i != width - 1)
		{
		
		printCharAt(traco_ver, i+x, y, attributes);
		printCharAt(traco_ver, i+x, height-1+y, attributes);
		
			i++;
		}

	printStringAt(title, x, y+2, attributes);
	
	return true;
}

